package com.styytech.dadabao.utils;

import com.styytech.dadabao.bean.BankCard;
import com.styytech.dadabao.bean.BankItem;
import com.styytech.dadabao.bean.Banner;
import com.styytech.dadabao.bean.InvestmentAmount;
import com.styytech.dadabao.bean.ListData;
import com.styytech.dadabao.bean.MyMessage;
import com.styytech.dadabao.bean.News;
import com.styytech.dadabao.bean.Notice;
import com.styytech.dadabao.bean.RecommendProduct;
import com.styytech.dadabao.bean.SaleRecord;
import com.styytech.dadabao.bean.TransactionDetails;
import com.styytech.dadabao.bean.UserAccount;
import com.styytech.dadabao.bean.UserRecord;
import com.styytech.dadabao.bean.ZfbItem;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.constant.ConstantsServerUrl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

public class ParseJsonUtils {

    /**
     * 返回页数，列表
     *
     * @return
     */
    public static ListData ParseListData(JSONArray jsonArray, int httpType) {
        LinkedList<Object> getList = new LinkedList<Object>();
        ListData listData = new ListData();
        if (jsonArray == null || jsonArray.length() <= 0) {
            listData.setDataList(getList);
            return listData;
        }
        getList = getDataList(jsonArray, httpType); // 根据类型解析列表
        listData.setDataList(getList);
        return listData;
    }

    /**
     * 根据类型解析列表
     *
     * @param jsonArray
     * @param dataType
     * @return
     */
    private static LinkedList<Object> getDataList(JSONArray jsonArray,
                                                  int dataType) {
        LinkedList<Object> getList = new LinkedList<Object>(); // 列表
        if (jsonArray == null) {
            return getList;
        } else if (jsonArray.length() == 0) {
            return getList;
        } else {
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    Object obj = null;
                    switch (dataType) {
                        case ConstantsCommon.DATA_SRC_NEWS: //
                            obj = parseJsonNewInfo(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_PROJECT: //
                            obj = dataParseProduct(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_RECORD: //
                            obj = parseSaleRecord(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_BANKCARD: // 解析已绑定银行卡列表数据
                            obj = parseBankCardList(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_BANK:
                            obj = parseBank(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_USER_RECORD:
                            obj = parseUserRecord(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_NOTICE:// 服务公告列表数据
                            obj = parseNoticeRecord(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_BANNER:// 服务公告列表数据
                            obj = parseBannerRecord(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_USER_TRANSACTION:
                            //用户交易明细
                            obj = parseTransaction(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_MESSAGE:// 站内消息列表数据
                            obj = parseMessageRecord(jsonArray.getJSONObject(i));
                            break;
                        case ConstantsCommon.DATA_SRC_ZFB:
                            obj = dataParsezfb(jsonArray.getJSONObject(i));
                            break;
                        default:
                            break;
                    }
                    if (obj != null) {
                        getList.add(obj);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return getList;
    }

    /**
     * 解析新闻
     */
    public static News parseJsonNewInfo(JSONObject newJSONObject) {
        News newInfo = new News();
        if (newJSONObject == null) {
            return newInfo;
        }
        try {
            newInfo.setId(newJSONObject.has("NEWS_ID") ? newJSONObject
                    .getLong("NEWS_ID") : -1);
            newInfo.setNewTitle(newJSONObject.has("TITLE") ? newJSONObject
                    .getString("TITLE") : "");
            newInfo.setNewImgUrl(newJSONObject.has("IMAGE_URL") ? ConstantsServerUrl.server
                    + newJSONObject.getString("IMAGE_URL")
                    : "");
            newInfo.setNewUrl(newJSONObject.has("NEWS_URL") ? newJSONObject
                    .getString("NEWS_URL") : "");
            newInfo.setReadNum(newJSONObject.has("READ_TIMES") ? newJSONObject
                    .getInt("READ_TIMES") : 0);
            newInfo.setNewdate(newJSONObject.has("AUDIT_TIME") ? newJSONObject
                    .getString("AUDIT_TIME") : "0");

            newInfo.setImageList(newJSONObject.has("IMAGELIST") ? newJSONObject
                    .getJSONArray("IMAGELIST").toString() : "");

            newInfo.setShareTimes(newJSONObject.has("SHARE_TIMES") ? newJSONObject
                    .getInt("SHARE_TIMES") : 0);

            newInfo.setIsImageNews(newJSONObject.has("IS_IMAGENEWS") ? newJSONObject
                    .getInt("IS_IMAGENEWS") : 0);
            newInfo.setContent(newJSONObject.has("CONTENT") ? newJSONObject
                    .getString("CONTENT") : "");
            newInfo.setSubContent(newJSONObject.has("CONTENT") ? newJSONObject
                    .getString("CONTENT") : "");
            newInfo.setShareNewsUrl(newJSONObject.has("NEWS_WEB_URL") ? newJSONObject
                    .getString("NEWS_WEB_URL") : "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return newInfo;
    }

    /**
     * 解析项目
     */

    public static RecommendProduct dataParseProduct(JSONObject jsonObjectApp) {

        RecommendProduct recommendProduct = new RecommendProduct();
        try {
            //id
            recommendProduct.setId(jsonObjectApp.has("productId") ? jsonObjectApp.getString("productId")
                    : "");
            //名字
            recommendProduct.setProductName(jsonObjectApp.has("productName") ? jsonObjectApp.getString("productName")
                    : "");
            //收益率
            recommendProduct.setExpectedReturnRatio(jsonObjectApp.has("expectedReturnRatio") ? jsonObjectApp.getString("expectedReturnRatio")
                    : "");
            //期限
            recommendProduct.setTimeLimit(jsonObjectApp.has("timeLimit") ? jsonObjectApp.getString("timeLimit")
                    : "0");
            //规模
            recommendProduct.setTotalCredit(jsonObjectApp.has("totalCredit") ? jsonObjectApp
                    .getDouble("totalCredit") : 0);
            //已售金额
            recommendProduct.setProgress(jsonObjectApp.has("progress") ? jsonObjectApp
                    .getDouble("progress") : 0);
            //投资人数
            recommendProduct.setPeople_num(jsonObjectApp.has("investNumber") ? jsonObjectApp
                    .getString("investNumber") : "0");
            //产品编号
            recommendProduct.setProduct_no(jsonObjectApp.has("productNo") ? jsonObjectApp.getString("productNo")
                    : "");
            //起投金额
            recommendProduct.setStart_money(jsonObjectApp.has("inceptMoney") ? jsonObjectApp.getDouble("inceptMoney")
                    : 0);
            //跟投金额
            recommendProduct.setStepMoney(jsonObjectApp.has("stepMoney") ? jsonObjectApp.getDouble("stepMoney")
                    : 0);
            //产品是否到期(0:过期  1:未过期)
            recommendProduct.setDueStatus(jsonObjectApp.has("dueStatus") ? jsonObjectApp.getString("dueStatus")
                    : "");
            //产品是否售完(0:已卖完  1:未卖完)
            recommendProduct.setLeftCredit(jsonObjectApp.has("leftCredit") ? jsonObjectApp.getString("leftCredit")
                    : "");
            //产品销售状态(0:草稿 1:在售 2:停售)
            recommendProduct.setSaleStatus(jsonObjectApp.has("saleStatus") ? jsonObjectApp.getString("saleStatus")
                    : "");
            //开放购买时间
            recommendProduct.setBuyTime(jsonObjectApp.has("buyTime") ? jsonObjectApp.getString("buyTime")
                    : "");
            //项目类型
            recommendProduct.setProductType(jsonObjectApp.has("productType") ? jsonObjectApp.getString("productType")
                    : "");
            //还款方式
            recommendProduct.setRepaymentMethod(jsonObjectApp.has("repaymentMethod") ? jsonObjectApp.getString("repaymentMethod")
                    : "");

            //产品基础描述
            recommendProduct.setBasicInformation(jsonObjectApp.has("productDesc") ? jsonObjectApp.getString("productDesc")
                    : "");
            //产品保理信息(保理机构，保理业务描述 保理公司简介 保理公司建议)
            recommendProduct.setScienceInformation("<b>保理机构:</b><br>"+(jsonObjectApp.has("factoringOrg") ? jsonObjectApp.getString("factoringOrg")
                    : "")+"<br><b>保理业务描述:</b><br>"+(jsonObjectApp.has("factoringBusiness") ? jsonObjectApp.getString("factoringBusiness")
                    : "")+"<br><b>保理公司简介:</b><br>"+(jsonObjectApp.has("factoringDesc") ? jsonObjectApp.getString("factoringDesc")
                    : "")+"<br><b>保理公司建议:</b><br>"+(jsonObjectApp.has("factoringSuggest") ? jsonObjectApp.getString("factoringSuggest")
                    : ""));
            //风险保障(还款来源+风控措施)
            recommendProduct.setRiskGuarantee("<b>还款来源:</b><br>"+(jsonObjectApp.has("refundSource") ? jsonObjectApp.getString("refundSource")
                    : "")+"<br><b>风控措施:</b><br>"+(jsonObjectApp.has("controlStep") ? jsonObjectApp.getString("controlStep")
                    : ""));
            //基础交易材料
            recommendProduct.setBasicTrading(jsonObjectApp.has("orderAttach") ? jsonObjectApp.getString("orderAttach")
                    : "");
            //保理业务材料
            recommendProduct.setFactoringBusiness(jsonObjectApp.has("factoringAttach") ? jsonObjectApp.getString("factoringAttach")
                    : "");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return recommendProduct;
    }

    /**
     * 解析投资金额
     */

    public static InvestmentAmount dataParseInvestmentAmount(JSONObject jsonObjectApp) {

        InvestmentAmount investmentAmount = new InvestmentAmount();
        try {
            //产品ID
            investmentAmount.setProductId(jsonObjectApp.has("productId") ? jsonObjectApp.getString("productId")
                    : "");
            //项目可投资金额
            investmentAmount.setLeftCredit(jsonObjectApp.has("leftCredit") ? jsonObjectApp.getDouble("leftCredit")
                    : 0);
            //项目可投资金额（格式化）
            investmentAmount.setLeftCreditF(jsonObjectApp.has("leftCreditF") ? jsonObjectApp.getString("leftCreditF")
                    : "");
            //用户账户余额(格式化)
            investmentAmount.setAccountBalanceF(jsonObjectApp.has("accountBalanceF") ? jsonObjectApp.getString("accountBalanceF") : "");
            //用户账户余额
            investmentAmount.setAccountBalance(jsonObjectApp.has("accountBalance") ? jsonObjectApp.getDouble("accountBalance")
                    : 0);
            //可用优惠劵(元)
            investmentAmount.setCoupon(jsonObjectApp.has("coupon") ? jsonObjectApp.getDouble("coupon")
                    : 0);
            //起投金额
            investmentAmount.setInceptMoney(jsonObjectApp.has("inceptMoney") ? jsonObjectApp.getDouble("inceptMoney") : 0);
            //跟投金额
            investmentAmount.setStepMoney(jsonObjectApp.has("stepMoney") ? jsonObjectApp.getDouble("stepMoney") : 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return investmentAmount;
    }

    /**
     * 解析投资记录
     */

    public static SaleRecord parseSaleRecord(JSONObject jsonObjectApp) {

        SaleRecord investmentAmount = new SaleRecord();
        try {
            //产品ID
            investmentAmount.setUserName(jsonObjectApp.has("mobile") ? jsonObjectApp.getString("mobile")
                    : "");
            //项目可投资金额
            investmentAmount.setInvestmentAmount(jsonObjectApp.has("orderMoney") ? jsonObjectApp.getString("orderMoney")
                    : "");
            //用户账户余额
            investmentAmount.setInvestmentTime(jsonObjectApp.has("createTime") ? jsonObjectApp.getString("createTime")
                    : "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return investmentAmount;
    }

    /**
     * 解析用户投资记录
     */

    public static UserRecord parseUserRecord(JSONObject jsonObjectApp) {
        UserRecord investmentAmount = new UserRecord();
        try {
            //产品名称
            investmentAmount.setProductName(jsonObjectApp.has("productName") ? jsonObjectApp.getString("productName")
                    : "");
            //投资金额
            investmentAmount.setMoney(jsonObjectApp.has("money") ? jsonObjectApp.getString("money")
                    : "");
            //还款状态
            investmentAmount.setStatus(jsonObjectApp.has("status") ? jsonObjectApp.getString("status")
                    : "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return investmentAmount;
    }

    /**
     * 解析服务公告列表记录
     */

    public static Notice parseNoticeRecord(JSONObject jsonObjectApp) {
        Notice notice = new Notice();
        String noticeId;//公告ID
        String title;//公告标题
        String content;//公告内容
        String publishTime;//发布时间
        String type;//公告类型
        String profile;//公告内容简介
        try {
            JSONObject json = jsonObjectApp;
            title = json.has("title") ? json.getString("title") : null;
            content = json.has("content") ? json.getString("content") : null;
            publishTime = json.has("publishTime") ? json.getString("publishTime") : null;
            profile = json.has("profile") ? json.getString("profile") : null;
            notice.setTitle(title);
            notice.setContent(content);
            notice.setPublishTime(publishTime);
            notice.setProfile(profile);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return notice;
    }

    /**
     * 解析广告图列表记录
     */

    public static Banner parseBannerRecord(JSONObject jsonObjectApp) {
        Banner banner = new Banner();
        String bId;//广告图ID
        String bTitle;//标题
        String bSort;//排序键
        String bType;//类型0:不可跳转，1可跳转
        String url;//图片请求url
        String recordId;// 项目id
        try {
            JSONObject json = jsonObjectApp;
            bId = json.has("bId") ? json.getString("bId") : null;
            bTitle = json.has("bTitle") ? json.getString("bTitle") : null;
            bSort = json.has("bSort") ? json.getString("bSort") : null;
            bType = json.has("bType") ? json.getString("bType") : null;
            url = json.has("url") ? json.getString("url") : null;
            recordId = json.has("recordId") ? json.getString("recordId") : null;
            banner.setbId(bId);
            banner.setbSort(bSort);
            banner.setbTitle(bTitle);
            banner.setbType(bType);
            banner.setUrl(url);
            banner.setRecordId(recordId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return banner;
    }

    /**
     * 解析站内通知列表记录
     */

    public static MyMessage parseMessageRecord(JSONObject jsonObjectApp) {
        MyMessage message = new MyMessage();
        int userMessageId;//用户消息ID
        String title;//标题
        String createTime;//创建时间
        String messageContent;//消息内容
        int status;//消息状态(0:未读 1:已读)
        try {
            JSONObject json = jsonObjectApp;
            userMessageId = json.has("userMessageId") ? json.getInt("userMessageId") : 0;
            title = json.has("title") ? json.getString("title") : null;
            messageContent = json.has("messageContent") ? json.getString("messageContent") : null;
            createTime = json.has("createTime") ? json.getString("createTime") : null;
            status = json.has("status") ? json.getInt("status") : 0;
            message.setUserMessageId(userMessageId);
            message.setTitle(title);
            message.setMessageContent(messageContent);
            message.setCreateTime(createTime);
            message.setStatus(status);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 解析用户交易明细
     */

    public static TransactionDetails parseTransaction(JSONObject jsonObjectApp) {
        TransactionDetails investmentAmount = new TransactionDetails();
        try {
            //资金行为
            investmentAmount.setFund_behavior(jsonObjectApp.has("status") ? jsonObjectApp.getString("status")
                    : "");
            //操作金额
            investmentAmount.setOperating_amount(jsonObjectApp.has("money") ? jsonObjectApp.getString("money")
                    : "");
            //交易时间
            investmentAmount.setTime(jsonObjectApp.has("createTime") ? jsonObjectApp.getString("createTime")
                    : "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return investmentAmount;
    }

    /**
     * 解析银行列表
     */

    public static BankItem parseBank(JSONObject jsonObjectApp) {

        BankItem bankItem = new BankItem();
        try {
            //用户绑定ID
            bankItem.setUserCardId(jsonObjectApp.has("userCardId") ? jsonObjectApp.getString("userCardId") : "");
            //用户ID
            bankItem.setUserId(jsonObjectApp.has("userId") ? jsonObjectApp.getString("userId") : "");
            //账户名称（银行名称）
            bankItem.setBankName(jsonObjectApp.has("bankName") ? jsonObjectApp.getString("bankName") : "");
            //用户姓名
            bankItem.setAccountName(jsonObjectApp.has("accountName") ? jsonObjectApp.getString("accountName") : "");
            //账户号（银行卡号）
            bankItem.setAccountNo(jsonObjectApp.has("accountNo") ? jsonObjectApp.getString("accountNo") : "");
            //账户类型（1:银行卡2:支付宝）
            bankItem.setAccountType(jsonObjectApp.has("accountType") ? jsonObjectApp.getInt("accountType") : 1);
            //账户状态(1绑定0解绑)
            bankItem.setAccountStatus(jsonObjectApp.has("accountStatus") ? jsonObjectApp.getInt("accountStatus") : 1);
            bankItem.setIsSelect(false);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return bankItem;
    }

    /**
     * 解析银行卡已绑定的列表数据
     */

    public static BankCard parseBankCardList(JSONObject jsonObjectApp) {
        BankCard bankCard = new BankCard();
        String userCardId = null;//用户绑定ID
        String accountName = null;
        String accountNo = null;
        String bankName = null;
        try {
            JSONObject json = jsonObjectApp;
            userCardId = json.has("userCardId") ? json.getString("userCardId") : null;
            accountName = json.has("accountName") ? json.getString("accountName") : null;
            accountNo = json.has("accountNo") ? json.getString("accountNo") : null;
            bankName = json.has("bankName") ? json.getString("bankName") : null;
            bankCard.setUserCardId(userCardId);
            bankCard.setAccountName(accountName);
            bankCard.setBankName(bankName);
            bankCard.setAccountNo(accountNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return bankCard;
    }

    /**
     * 解析用户信息
     */
    public static UserAccount parseJsonUserAccount(JSONObject json) {
        UserAccount user = new UserAccount();
        if (json == null) {
            return user;
        }
        try {
            user.setUserId((json.has("userId") ? json.getInt("userId") : 0));
            user.setUserAccountId((json.has("userAccountId") ? json.getInt("userAccountId")
                    : 0));
            user.setAccountbalance((json.has("accountBalance") ? json.getDouble("accountBalance") : -1));
            user.setAvailableBalance((json.has("availableBalance") ? json.getDouble("availableBalance") : -1));
            user.setAccountbalanceF((json.has("accountBalanceF") ? json.getString("accountBalanceF") : ""));
            user.setAvailableBalanceF((json.has("availableBalanceF") ? json.getString("availableBalanceF") : ""));
            user.setAssignedIncomeAmount((json.has("assignedIncomeAmount") ? json.getString("assignedIncomeAmount")
                    : ""));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 解析关于我们信息
     */
    public static Object parseJsonAboutUs(JSONObject json) {
        // AboutUs aboutus = new AboutUs();
        // Log.i("123",json+"");
        // if (json == null) {
        // return aboutus;
        // }
        // try {
        // aboutus.setCompanyLogos((json.has("LOGO") ? json.getString("LOGO")
        // : ""));
        // aboutus.setCompanyName((json.has("TITLE") ? json.getString("TITLE")
        // : ""));
        // aboutus.setContent((json.has("CONTENT") ? json.getString("CONTENT")
        // : ""));
        // aboutus.setAboutusId((json.has("ABOUT_US_ID") ? json
        // .getInt("ABOUT_US_ID") : -1));
        //
        // } catch (JSONException e) {
        // e.printStackTrace();
        // }
        return null;
    }

    /**
     * @param imageList
     * @return
     */
    public static String[] setList(String imageList) {
        JSONArray json = null;
        try {
            json = new JSONArray(imageList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json == null) {
            return null;
        } else {
            int posiTion = json.length();
            String list[] = new String[posiTion];
            for (int i = 0; i < list.length; i++) {
                try {
                    list[i] = ConstantsServerUrl.server + (String) json.get(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            return list;
        }

    }

    public static String[] setContentList(String contentList) {
        JSONArray json = null;
        try {
            json = new JSONArray(contentList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json == null) {
            return null;
        } else {
            int posiTion = json.length();
            String list[] = new String[posiTion];
            for (int i = 0; i < list.length; i++) {
                try {
                    list[i] = (String) json.get(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            return list;
        }

    }

    /**
     * 解析支付宝订单信息
     */

    public static ZfbItem dataParsezfb(JSONObject jsonObjectApp) {

        ZfbItem bankItem = new ZfbItem();
        try {
            //订单唯一编号
            bankItem.setFlowNo(jsonObjectApp.has("flowNo") ? jsonObjectApp.getString("flowNo") : "");
            //合作者身份ID
            bankItem.setPartner(jsonObjectApp.has("partner") ? jsonObjectApp.getString("partner") : "");
            //商户收款账户
            bankItem.setSeller(jsonObjectApp.has("seller") ? jsonObjectApp.getString("seller") : "");
            //商品描述
            bankItem.setBody(jsonObjectApp.has("body") ? jsonObjectApp.getString("body") : "");
            //商品名称
            bankItem.setSubject(jsonObjectApp.has("subject") ? jsonObjectApp.getString("subject") : "");
            //商品金额(订单总价)
            bankItem.setTotalFee(jsonObjectApp.has("totalFee") ? jsonObjectApp.getString("totalFee") : "");
            //服务器端通知路径
            bankItem.setNotifyUrl(jsonObjectApp.has("notifyUrl") ? jsonObjectApp.getString("notifyUrl") : "");
            //商家私钥
            bankItem.setPrivateKey(jsonObjectApp.has("privateKey") ? jsonObjectApp.getString("privateKey") : "");
            //商家公钥
            bankItem.setPublicKey(jsonObjectApp.has("publicKey") ? jsonObjectApp.getString("publicKey") : "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return bankItem;
    }

}
